package com.phiture.erp.sale.web.controller.admin.api;

import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.phiture.erp.sale.api.pojo.resp.ErpSaleOrderItemResp;
import com.phiture.erp.sale.api.pojo.resp.ErpSaleOrderResp;
import com.phiture.erp.sale.api.service.ErpSaleApi;
import com.phiture.erp.sale.dal.entity.ErpSaleOrderDO;
import com.phiture.erp.sale.dal.entity.ErpSaleOrderItemDO;
import com.phiture.erp.sale.dal.mapper.ErpSaleOrderItemMapper;
import com.phiture.erp.sale.dal.mapper.ErpSaleOrderMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ErpSaleApiServiceImpl implements ErpSaleApi {

    @Resource
    private ErpSaleOrderItemMapper erpSaleOrderItemMapper;

    @Resource
    private ErpSaleOrderMapper erpSaleOrderMapper;

    @Override
    public ErpSaleOrderItemResp getSaleOrderItemById(Long id) {
        return BeanUtils.toBean(erpSaleOrderItemMapper.selectById(id), ErpSaleOrderItemResp.class);
    }

    @Override
    public int updateSaleOrderItem(ErpSaleOrderItemResp item) {
        return erpSaleOrderItemMapper.updateById(BeanUtils.toBean(item, com.phiture.erp.sale.dal.entity.ErpSaleOrderItemDO.class));
    }

    // 根据销售订单ID查询销售订单项
    @Override
    public List<ErpSaleOrderItemResp> getSaleOrderItemsByOrderId(Long orderId) {
        return erpSaleOrderItemMapper.selectList(Wrappers.<ErpSaleOrderItemDO>lambdaQuery()
                .eq(ErpSaleOrderItemDO::getOrderId, orderId))
                .stream()
                .map(item -> BeanUtils.toBean(item, ErpSaleOrderItemResp.class))
                .collect(Collectors.toList());
    }

    @Override
    public ErpSaleOrderResp getSaleOrderById(Long id) {
        return BeanUtils.toBean(erpSaleOrderMapper.selectById(id), ErpSaleOrderResp.class);
    }

    @Override
    public int updateSaleOrderMrpFlag(Long id, Integer mrpFlag) {
        // 根据id,更新mrpFlag
        return erpSaleOrderMapper.update(null, Wrappers.<ErpSaleOrderDO>lambdaUpdate()
                .set(ErpSaleOrderDO::getMrpFlag, mrpFlag)
                .eq(ErpSaleOrderDO::getId, id));
    }

    @Override
    public int updateSaleOrderItemMrpFlag(Long id, Integer mrpFlag) {
        return erpSaleOrderItemMapper.update(null, Wrappers.<ErpSaleOrderItemDO>lambdaUpdate()
                .set(ErpSaleOrderItemDO::getMrpFlag, mrpFlag)
                .eq(ErpSaleOrderItemDO::getId, id));
    }
}
